<template>
	<div class="px-1 py-1 relative cursor-pointer" @click="onTranslate">
		<base-ellipsis :line-clamp="5" :text="showContent"></base-ellipsis>
		<base-icon
			v-if="!isMe"
			class="absolute -right-[2px] -top-[6px]"
			:class="{
				'animate-spin opacity-50': loading,
				'text-primary': !showTranslated,
				'text-success': showTranslated
			}"
			name="openai"></base-icon>
	</div>
</template>

<script lang="ts" setup>
import { BaseIcon, BaseEllipsis } from '@/components/base/'
import { PropType, computed, ref } from 'vue'
import { FeedType } from '@/types'
import { translateFeeds } from '@/api/feed'
import { useRequest } from '@/hooks'
import { useAppStore } from '@/store'

const props = defineProps({
	data: {
		type: Object as PropType<FeedType>,
		required: true
	},
	isMe: {
		type: Boolean,
		default: false
	}
})

const appStore = useAppStore()

const translatedContent = ref('')

const showTranslated = ref(false)

const showContent = computed(() => {
	if (showTranslated.value && translatedContent.value) {
		return translatedContent.value
	} else {
		return props.data.content
	}
})

const { run, loading } = useRequest(translateFeeds, {
	onSuccess: (data: any) => {
		translatedContent.value = data.content
		showTranslated.value = true
	}
})

const onTranslate = () => {
	if (props.isMe) {
		return
	}
	if (translatedContent.value) {
		showTranslated.value = !showTranslated.value
	} else {
		run({
			id: props.data.id,
			locale: appStore.lang
		})
	}
}
</script>
